package edu.utexas.mapreduce;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.Map.Entry;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

/**
 * SAX parser event handler for map output files.  Groups all values associated
 * with the same map key.  No validity checks on the XML input are performed.  
 * It is assumed that the parser has validation enabled.
 */
public class XMLMapOutputHandler extends DefaultHandler {

	  private Map<String, List<String>> keyMap = new TreeMap<String, List<String>>();
	  private StringBuilder elementData;
	  private String key;
	  private String value;
	  
	  public void startElement(String namespaceURI, String localName, String qualifiedName, Attributes atts) throws SAXException {
		  if (localName.equals(XML.KEY) || localName.equals(XML.VALUE)) {
			  elementData = new StringBuilder();
		  }
	  }

	  public void endElement(String namespaceURI, String localName, String qualifiedName) throws SAXException {
		 
		  if (localName.equals(XML.KEY)) {
			  key = elementData.toString();
		  }
		  
		  if (localName.equals(XML.VALUE))  {
			  value = elementData.toString();
		  }
		  
		  if (localName.equals(XML.MAP)) {
			  List<String> list = keyMap.get(key);
			  if (list == null) {
				  list = new ArrayList<String>();
				  keyMap.put(key, list);
			  }
			  list.add(value);
		  }
	  }

	  public void characters(char[] ch, int start, int length) throws SAXException {
		  elementData.append(ch, start, length);		  
	  }
	  
	  Set<Entry<String, List<String>>> entrySet() {
		  return keyMap.entrySet();
	  }
}
